package com.yilin.platform.base_core.tools.cmbc.utils;

import com.yilin.platform.base_core.commons.utils.DateTimeUtil;
import com.yilin.platform.base_core.commons.utils.XmlUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
@Component
public class XmlBuilder {

//=========================程序运行时使用 记得修改XmlBodyTools里面的reqURL============================================
    private static String clientId="2300104032";//
    private static String userId="2300104032007";
    private static String userPswd="544mna";//
    private static String language="chs";//
    private static String appId="nsbdes";//
    private static String appVer="201";//
    @Value("${cmbc-bank-enterprise.client-id}")
    private  String clientIds;
    @Value("${cmbc-bank-enterprise.user-id}")
    private  String userIds;
    @Value("${cmbc-bank-enterprise.user-pswd}")
    private  String userPswds ;
    @Value("${cmbc-bank-enterprise.language}")
    private  String languages;
    @Value("${cmbc-bank-enterprise.app-id}")
    private  String appIds;
    @Value("${cmbc-bank-enterprise.app-ver}")
    private  String appVers;

    @PostConstruct
    public void setClientIds() {clientId = this.clientIds;}
    @PostConstruct
    public void setUserIds() {
        userId = this. userIds;
    }
    @PostConstruct
    public void setUserPswds() {
      userPswd =  this.userPswds;
    }
    @PostConstruct
    public void setLanguages() {
       language = this. languages;
    }
    @PostConstruct
    public void setAppIds() {
        appId =  this.appIds;
    }
    @PostConstruct
    public void setAppVers() {
        appVer =  this.appVers;
    }

    //    请求xml
    public static String convertToReqXml( XmlReturnMap returnMap) {
        try {
            StringBuilder xmlTag = new StringBuilder();
            xmlTag.append("<?xml version=\"1.0\" encoding=\"GB2312\"?>")
                    .append("<CMBC header=\"100\" version=\"100\" security=\"none\" lang=\"GB2312\" trnCode=\"").append(returnMap.getTrnCode()).append("\">")
                    .append("<requestHeader>")
                    .append("<dtClient>").append(DateTimeUtil.dateToString(new Date())).append("</dtClient>")
                    .append("<clientId>").append(clientId).append("</clientId>")
                    .append("<userId>").append(userId).append("</userId>")
                    .append("<userPswd>").append(userPswd).append("</userPswd>")
                    .append("<language>").append(language).append("</language>")
                    .append("<appId>").append(appId).append("</appId>")
                    .append("<appVer>").append(appVer).append("</appVer>")
                    .append("</requestHeader>");
            String xmlString = XmlUtils.mapToXml(returnMap.getBodyMap());
            xmlTag.append("<xDataBody>").append(xmlString == null ? "" : xmlString).append("</xDataBody>").append("</CMBC>");
            return xmlTag.toString();
        } catch (Exception e) {
            return null;
        }
    }

    public static CmbcResData parseXmlDataResponse(String xmlString, String trnCode) {
        CmbcResData cmbcResData = new CmbcResData();
        try {
            Map<String, Object> cmBcMap = XmlUtils.multilayerXmlToMap(xmlString);
            Map<String, Object> responseHeader = (Map<String, Object>) cmBcMap.get("responseHeader");

            String dtServer = (String) responseHeader.get("dtServer");
            String dtClient = (String) responseHeader.get("dtClient");
            String clientId = (String) responseHeader.get("clientId");
            String userId = (String) responseHeader.get("userId");
            String userPswd = (String) responseHeader.get("userPswd");
            String language = (String) responseHeader.get("lanaguge");
            Map<String, Object> status = (Map<String, Object>) responseHeader.get("status");
            String code = (String) status.get("code");
            String severity = (String) status.get("severity");
            String message = (String) status.get("message");
            String xmlBodyData = "<xDataBody>" + XmlUtils.mapToXml((Map<String, Object>) cmBcMap.get("xDataBody")) + "</xDataBody>";
            Map<String, Object> xmlbody = (Map<String, Object>) cmBcMap.get("xDataBody");
            cmbcResData.setDtServer(dtServer);
            cmbcResData.setDtClient(dtClient);
            cmbcResData.setTrnCode(trnCode);
            cmbcResData.setClientId(clientId);
            cmbcResData.setUserId(userId);
            cmbcResData.setUserPswd(userPswd);
            cmbcResData.setLanguage(language);
            cmbcResData.setCode(code);
            cmbcResData.setSeverity(severity);
            cmbcResData.setMessage(message);
            cmbcResData.setDataXml(xmlBodyData);
            cmbcResData.setDataMap(xmlbody);
            cmbcResData.setXmlResData(xmlString);
        } catch (Exception e) {
            cmbcResData.setHtmlResData(null);
        }
        return cmbcResData;
    }

    // 设置公共属性
    public static void setCommonFields(Object entity, CmbcResData cmbcResData) {
        try {
            Method setDtServerMethod = entity.getClass().getMethod("setDtServer", String.class);
            setDtServerMethod.invoke(entity, cmbcResData.getDtServer());

            Method setUserKeyMethod = entity.getClass().getMethod("setDtClient", String.class);
            setUserKeyMethod.invoke(entity, cmbcResData.getDtClient());

            Method setClientIdMethod = entity.getClass().getMethod("setClientId", String.class);
            setClientIdMethod.invoke(entity, cmbcResData.getClientId());

            Method setUserIdMethod = entity.getClass().getMethod("setUserId", String.class);
            setUserIdMethod.invoke(entity, cmbcResData.getUserId());

            Method setUserPswdMethod = entity.getClass().getMethod("setUserPswd", String.class);
            setUserPswdMethod.invoke(entity, cmbcResData.getUserPswd());

            Method setLanguageMethod = entity.getClass().getMethod("setLanguage", String.class);
            setLanguageMethod.invoke(entity, cmbcResData.getLanguage());

            Method setCodeMethod = entity.getClass().getMethod("setCode", String.class);
            setCodeMethod.invoke(entity, cmbcResData.getCode());

            Method setSeverityMethod = entity.getClass().getMethod("setSeverity", String.class);
            setSeverityMethod.invoke(entity, cmbcResData.getSeverity());

            Method setMessageMethod = entity.getClass().getMethod("setMessage", String.class);
            setMessageMethod.invoke(entity, cmbcResData.getMessage());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static <T> T convertXMLToObject(CmbcResData cmbcResData, Class<T> clazz) {
        try {
            StringReader reader = new StringReader(cmbcResData.getDataXml());
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            T obj = (T) unmarshaller.unmarshal(reader);
//            XmlBuilder.setCommonFields(obj, cmbcResData);//设置公共属性
            return obj;
        } catch (JAXBException e) {
            return null;
        }
    }

    public static void main(String[] args) throws JAXBException {
        String smls = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n</CMBC>";
        CmbcResData cmbcResData = parseXmlDataResponse(smls, "dd");
        System.out.println("");
    }


}
